<?php


namespace api\admin\controller;

use cmf\controller\RestBaseController;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Filesystem;

class UploadController extends RestBaseController
{
    //本地上传
    public function Upload()
    {
        $file = request()->file('file');
        $result = Filesystem::disk('public')->putFile('image',$file);
        if($result){
            $this->success('上传成功',[
                'url' => request()->domain() . '/storage/' . $result
            ]);
        }else{
            $this->error('上传失败');
        }

    }
    //七牛上传
    public function Qiniu()
    {
        $file = request()->file('file');
        if(!$file) {
            halt('file error');
        }
        // 七牛云配置
        $accessKey = config('app.qiniuOss.accessKey');
        $secretKey = config('app.qiniuOss.secretKey');
        $bucket = config('app.qiniuOss.bucket');
        // 构建鉴权对象
        $auth = new Auth($accessKey,$secretKey);
        //生成上传Token
        $token = $auth->uploadToken($bucket);

        //要上传文件的本地路径
        $filePath = $file->getPathname();

        //上传到储存后保存的文件名
        $key = time() . '.' . $file->getOriginalExtension();

        //构建UploadManager对象
        $uploadMgr = new UploadManager();
        //调用UploadManager的putFile方法进行文件的上传
        list($return, $error) = $uploadMgr->putFile($token, $key, $filePath);
        if ($error !== null) {
            //$this->error('上传失败');
            halt($error->message());
        } else {
            //var_dump($ret);
            $this->success('上传成功',[
                'url' => 'http://sel2c9g2q.hb-bkt.clouddn.com/'.$return['key'],
            ]);
        }
    }
}
